package xhwl.pulltorefresh;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import xhwl.pulltorefresh.callback.PullToRefreshListener;

/**
 * Created by Kun on 2017/2/7.
 * GitHub: https://github.com/AndroidKun
 * CSDN: http://blog.csdn.net/a1533588867
 * Description:PullToRefreshRecyclerView
 */

public class PullToRefreshRecyclerView extends LinearLayout {
    private static final int TYPE_EMPTY_VIEW = 10002;
    private View emptyView;
    RefreshLayout refreshLayout;
    RecyclerView recylerView;

    private final RecyclerView.AdapterDataObserver dataObserver = new DataObserver();
    private PullToRefreshRecyclerViewAdapter pullToRefreshRecyclerViewAdapter;

    private PullToRefreshListener pullToRefreshListener;
    public PullToRefreshRecyclerView(Context context) {
        this(context, null);
    }

    public PullToRefreshRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PullToRefreshRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        View view=LayoutInflater.from(context).inflate(R.layout.layout_pulltorefresh_recyleview,this);
        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        recylerView= (RecyclerView) view.findViewById(R.id.recylerView);
        recylerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        this.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if(pullToRefreshListener!=null){
                    pullToRefreshListener.onRefresh();
                }
            }
        });
        this.refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if(pullToRefreshListener!=null){
                    pullToRefreshListener.onLoadMore();
                }
            }
        });
    }
    public RefreshLayout getRefreshLayout(){
        return refreshLayout;
    }
    public void setPullRefreshEnabled(boolean pullRefreshEnabled) {
        this.refreshLayout.setEnableRefresh(pullRefreshEnabled);

    }

    public void setLoadingMoreEnabled(boolean loadingMoreEnabled) {
        this.refreshLayout.setEnableLoadmore(loadingMoreEnabled);
    }

    public void setPullToRefreshListener(PullToRefreshListener pullToRefreshListener) {
        this.pullToRefreshListener = pullToRefreshListener;
    }
    public void setAdapter(RecyclerView.Adapter adapter) {
        pullToRefreshRecyclerViewAdapter = new PullToRefreshRecyclerViewAdapter(adapter);
        recylerView.setAdapter(pullToRefreshRecyclerViewAdapter);
        adapter.registerAdapterDataObserver(dataObserver);
        dataObserver.onChanged();
//        recylerView.setAdapter(adapter);
    }

    public RecyclerView.Adapter getAdapter() {
        if (pullToRefreshRecyclerViewAdapter != null) {
            return pullToRefreshRecyclerViewAdapter.getAdapter();
        }
        return null;
    }

    /**
     * 设置是否显示上次刷新时间
     */
    public void displayLastRefreshTime(boolean display){
    }


    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }


    public void setRefreshComplete() {
        if (refreshLayout.isEnableRefresh()) {
            refreshLayout.finishRefresh();
        }
    }

    public void setRefreshFail() {
        if (refreshLayout.isEnableRefresh()) {
            refreshLayout.finishRefresh();
        }
    }

    /**
     * 设置触发刷新的高度
     *
     * @param height
     */
    public void setRefreshLimitHeight(int height){
        refreshLayout.setHeaderHeightPx(height);
    }
    public void setLayoutManager(RecyclerView.LayoutManager layout) {
        recylerView.setLayoutManager(layout);
    }

    public void setLoadMoreComplete() {
        refreshLayout.finishLoadmore();

    }
    public void setLoadMoreFinished(){
        refreshLayout.setLoadmoreFinished(true);
    }

    public void setLoadMoreFail() {
        refreshLayout.finishLoadmore();
    }
    public void addOnScrollListener(RecyclerView.OnScrollListener listener){
        recylerView.addOnScrollListener(listener);
    }
    private class PullToRefreshRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private RecyclerView.Adapter adapter;

        public PullToRefreshRecyclerViewAdapter(RecyclerView.Adapter adapter) {
            this.adapter = adapter;
        }

        public RecyclerView.Adapter getAdapter() {
            return adapter;
        }

        private boolean isEmptyView(int position){
            return shouldDisplayEmptyView() && position==0;
        }
        /**
         * 是否需要显示EmptyView
         * @return
         */
        private boolean shouldDisplayEmptyView(){
            return adapter.getItemCount()==0 && emptyView!=null;
        }
        @Override
        public int getItemCount() {
            int count=0;
            if (adapter != null) {
                count = adapter.getItemCount();
            }
            //如果Adapter中没有数据 则多加1用于显示EmptyView
            if(shouldDisplayEmptyView()){
                count+=1;
            }
            return count;
        }

        @Override
        public int getItemViewType(int position) {
            if(shouldDisplayEmptyView()&& position==0){
                return TYPE_EMPTY_VIEW;
            }
            if (adapter != null) {
                return adapter.getItemViewType(position);
            }
            return 0;
        }



        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_EMPTY_VIEW ){
                return new SimpleViewHolder(emptyView);
            }
            return adapter.onCreateViewHolder(parent, viewType);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (isEmptyView(position)) {
                return;
            }
            if (adapter != null) {
               adapter.onBindViewHolder(holder, position);
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List<Object> payloads) {
            if (isEmptyView(position) ) {
                return;
            }
            if (adapter != null) {
                    if (payloads.isEmpty()) {
                        adapter.onBindViewHolder(holder, position);
                    } else {
                        adapter.onBindViewHolder(holder, position, payloads);
                    }
            }
        }

        @Override
        public long getItemId(int position) {
            if (adapter != null) {
                    return adapter.getItemId(position);
            }
            return -1;
        }

        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            if (manager instanceof GridLayoutManager) {
                final GridLayoutManager gridManager = ((GridLayoutManager) manager);
                gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return isEmptyView(position)
                                ? gridManager.getSpanCount() : 1;
                    }
                });
            }
            adapter.onAttachedToRecyclerView(recyclerView);
        }

        @Override
        public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
            adapter.onDetachedFromRecyclerView(recyclerView);
        }

        @Override
        public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
            super.onViewAttachedToWindow(holder);
            adapter.onViewAttachedToWindow(holder);
        }

        @Override
        public void onViewDetachedFromWindow(RecyclerView.ViewHolder holder) {
            adapter.onViewDetachedFromWindow(holder);
        }

        @Override
        public void onViewRecycled(RecyclerView.ViewHolder holder) {
            adapter.onViewRecycled(holder);
        }

        @Override
        public boolean onFailedToRecycleView(RecyclerView.ViewHolder holder) {
            return adapter.onFailedToRecycleView(holder);
        }

        @Override
        public void unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
            adapter.unregisterAdapterDataObserver(observer);
        }

        @Override
        public void registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
            adapter.registerAdapterDataObserver(observer);
        }

        private class SimpleViewHolder extends RecyclerView.ViewHolder {
            public SimpleViewHolder(View itemView) {
                super(itemView);
            }
        }

    }
    private class DataObserver extends RecyclerView.AdapterDataObserver {

        @Override
        public void onChanged() {
            if (pullToRefreshRecyclerViewAdapter != null) {
                pullToRefreshRecyclerViewAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeInserted(positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeChanged(positionStart, itemCount);
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeChanged(positionStart, itemCount, payload);
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemRangeRemoved(positionStart, itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            pullToRefreshRecyclerViewAdapter.notifyItemMoved(fromPosition, toPosition);
        }
    }
}
